package com.fneuch.web.navigation;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


public class GestionMenuInterceptor extends HandlerInterceptorAdapter {

	private List<MenuItem> menus;

	public GestionMenuInterceptor() {
		super();
		
	}

	public GestionMenuInterceptor(List<MenuItem> menus) {
		super();
		this.menus = menus;
	}
	
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
		if(modelAndView != null) {
			String nomVue = modelAndView.getViewName();
			selectionnerMenuCourant(nomVue, menus);
			modelAndView.addObject("menus", menus);
		}
	}

	
	public List<MenuItem> getMenus() {
		return menus;
	}

	public void setMenus(List<MenuItem> menus) {
		this.menus = menus;
	}

	private boolean selectionnerMenuCourant(String nomVue, List<MenuItem> menusTraites) {
		boolean selectionMenuAppliquer = false;
		for(MenuItem menuCourant : menusTraites) {
			selectionMenuAppliquer = menuCourant.getId().equals(nomVue);
			if(!selectionMenuAppliquer && 
					menuCourant.getMenuItems() != null && 
					!menuCourant.getMenuItems().isEmpty()) {
				selectionMenuAppliquer = selectionnerMenuCourant(nomVue, menuCourant.getMenuItems());
			}
			menuCourant.setSelected(selectionMenuAppliquer);
		}
		return selectionMenuAppliquer;
	}
}
